-- checks if a gun was added successfully, with all necessary informations
DROP FUNCTION IF EXISTS trigger_check_add_gun();
CREATE OR REPLACE FUNCTION trigger_check_add_gun()
RETURNS TRIGGER AS
$trigger_check_add_gun$
BEGIN
  IF NEW.fk_item IS NULL THEN
    RAISE EXCEPTION 'A gun must refer to an Item';
  END IF;

  IF NEW.durability < -1 OR NEW.durability > 100 THEN
    RAISE EXCEPTION 'gun (id: %) durability trouble', NEW.id_gunframes;
  END IF;

  RETURN NEW;

EXCEPTION WHEN OTHERS THEN
  RAISE WARNING '% - %', SQLERRM, SQLSTATE;
END;
$trigger_check_add_gun$ LANGUAGE plpgsql;


CREATE TRIGGER trigger_check_add_gun BEFORE INSERT OR UPDATE ON GUNFRAMES
  FOR EACH ROW EXECUTE PROCEDURE trigger_check_add_gun();
